# -*- coding: utf-8 -*-
# @Time    : 2024/1/23 20:54
# @Author  : micah
# @File    : 2.使用aiohttp完成异步爬虫任务.py
# @Software: PyCharm


import asyncio
from aiohttp import ClientSession

url = 'https://www.baidu.com'
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}


async def get_baidu():
    # 1.异步上下文管理器创建网络请求对象
    async with ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            # 1.看函数是否使用async声明
            # 2.看返回值是否是一个可等待的对象
            result = await response.text()
            print(result)


if __name__ == '__main__':
    # 当前的运行方式适合macOS/Linux去使用
    # asyncio.run(get_baidu())

    # windows
    loop = asyncio.get_event_loop()
    loop.run_until_complete(get_baidu())

